package indi.madoka.weeb.bean.factory;

import com.alibaba.fastjson.JSONObject;
import indi.madoka.weeb.bean.update.BaseUpdate;
import indi.madoka.weeb.enums.MessageType;
import indi.madoka.weeb.enums.NoticeType;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Arcueid
 */
@Component
public class UpdateFactory implements InitializingBean {
    protected static final Map<String, Class<? extends BaseUpdate>> MAP_TO_JAVA_CLASS = new HashMap<>();

    @Override
    public void afterPropertiesSet() {
        for (NoticeType noticeType : NoticeType.values()) {
            MAP_TO_JAVA_CLASS.put(noticeType.getValue(), noticeType.getUpdateNoticeClass());
        }
        for (MessageType messageType : MessageType.values()) {
            MAP_TO_JAVA_CLASS.put(messageType.getValue(), messageType.getUpdateMessageClass());
        }
    }

    /**
     * 获取对应上传类型的java对象
     *
     * @param type             上报消息的type字段 e.g: message_type,notice_type
     * @param updateJsonObject 上报的JsonObject
     * @return BaseUpdate的子类
     */
    @SuppressWarnings("unchecked")
    public <T extends BaseUpdate> T getUpdateInJavaObject(String type, JSONObject updateJsonObject) {
        return (T) JSONObject.toJavaObject(updateJsonObject,
                MAP_TO_JAVA_CLASS.get(type));
    }
}
